<template>
  <div class="product-management">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="formData" class="demo-form-inline">
      <el-form-item label="产品名称">
        <el-input v-model="formData.name" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item label="产品型号">
        <el-select
          v-model="formData.model"
          placeholder="全部"
          clearable
          style="width: 80px"
        >
          <el-option label="全部" value="" />
          <el-option label="安卓" value="10" />
          <el-option label="苹果" value="20" />
          <el-option label="鸿蒙" value="30" />
        </el-select>
      </el-form-item>

      <el-form-item label="产品状态">
        <el-select
          v-model="formData.status"
          placeholder="全部"
          clearable
          style="width: 80px"
        >
          <el-option label="全部" value="" />
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form style=" float: right; margin-right: 20px;margin-bottom: 20px">
      <el-button type="primary" round @click="add">添加</el-button>
      <el-button type="success" round>导入</el-button>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%" stripe>
      <el-table-column prop="product_id" label="产品编号" width="120" />
      <el-table-column prop="product_name" label="产品名称" />
      <el-table-column label="产品分类">
        <template #default="{ row }">
          {{ formatCategory(row) }}
        </template>
      </el-table-column>
      <el-table-column prop="model" label="型号" width="100" />
      <el-table-column
        prop="product_model"
        label="产品图号"
        width="120"
        align="center"
      />
      <el-table-column prop="inventory" label="库存" width="120" />
      <el-table-column label="创建人" width="120">
        <template v-slot:default>管理员</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            class="mt-2"
            inline-prompt
            :active-icon="Check"
            :inactive-icon="Close"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot="{ row }">
          <el-button type="primary" size="small" @click="update(row.product_id)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="del(row.product_id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div
      style="
        display: flex;
        justify-content: center;
        height: 50px;
        margin-top: 20px;
        line-height: 50px;
        text-align: right;
      "
    >
      <el-pagination
        background
        :page-size="pageSize"
        :page-sizes="[2, 5, 10, 20, 50]"
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
        @size-change="chgsize"
        @current-change="chgpg"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { Check, Close } from "@element-plus/icons-vue";
import {
  getProductList,
  updateProduct,
  deleteProductById
} from "@/api/product/product.js";
import { onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

//格式化产品分类
const typeMap = {
  10: "电脑",
  11: "手机",
  12: "耳机"
};

const categoryMap = {
  10: {
    1: "dell电脑",
    2: "天选电脑"
  },
  11: {
    1: "vivo手机",
    2: "小米手机"
  },
  12: {
    1: "漫步者耳机",
    2: "水月雨耳机"
  }
};

// 或者使用方法形式
const formatCategory = row => {
  return `${typeMap[row.product_type] || "未知类型"} > ${
    categoryMap[row.product_type]?.[row.product_category] || "未知分类"
  }`;
};

const router = useRouter();
const route = useRoute();

function add() {
  router.push("/product/add");
}

function update(id) {
  router.push({ path: "/product/update", query: { id } });
}

function del(id) {
  console.log(id);
  ElMessageBox.confirm("你确定要删除吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteProduct(id);
    })
    .catch(() => {});
  // 这里添加实际的删除逻辑
}

//根据id删除产品
async function deleteProduct(id) {
  let res = await deleteProductById(id);
  if (res.code == 200) {
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    initData();
  }
}

//状态切换
const handleStatusChange = row => {
  //console.log("状态变更:", row.product_id, row.status);
  // 这里调用API更新状态
  let data = {
    productId: row.product_id,
    status: row.status
  };
  updateProductStatus(data);
};

//根据id更改产品状态
async function updateProductStatus(data) {
  let res = await updateProduct(data);
  if (res.code == 200) {
    ElMessage({
      message: "修改成功",
      type: "success"
    });
  }
}

const page = ref(1); //当前页 默认第1页
const pageSize = ref(5); //每页记录数
const total = ref(0); //总记录数

//每页记录数变化
function chgsize(size) {
  //更改每页记录数
  pageSize.value = size;
  //从每页开始查询
  page.value = 1;
  //查询数据
  initData();
}

function chgpg(pg) {
  //更改当前页
  page.value = pg;
  //查询数据
  initData();
}

// 表单数据
const formData = ref({
  name: "",
  model: "",
  status: ""
});

// 表格数据
const tableData = ref([]);

async function initData() {
  let data = {
    page: page.value,
    pageSize: pageSize.value,
    productName: formData.value.name,
    model: formData.value.model,
    status: formData.value.status
  };
  let res = await getProductList(data);
  console.log(res);
  if (res.code == 200) {
    tableData.value = res.data.data;
    total.value = res.data.total;
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
  }
}

// 查询操作
const handleQuery = () => {
  // 这里添加实际的查询逻辑
  initData();
};

// 重置表单
const handleReset = () => {
  formData.value.model = "";
  formData.value.status = "";
  formData.value.name = "";
  initData();
};
onMounted(() => {
  initData();
});
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.demo-form-inline .el-form-item {
  margin-right: 20px;
}
</style>
